#!/bin/bash

# Two-level reboot: `tmt-reboot` extracts command line arguments, and
# calls `tmt-reboot-core` *while holding the tmt test pidfile lock!*
# That should assure the pidfile would exist and contain valid info.

[ -n "$TMT_DEBUG" ] && set -x

TMT_TEST_PIDFILE_LOCK="${TMT_TEST_PIDFILE_LOCK:-/var/tmp/tmt-test.pid}"

PATH=/sbin:/usr/sbin:$PATH

command=""
timeout=""
efi=True
while getopts "c:t:e" flag; do
    case "${flag}" in
        c) command="${OPTARG}";;
        t) timeout="${OPTARG}";;
        e) efi=False;;
        *) exit 1;;
    esac
done

if [ $efi = True ]; then
    if efibootmgr &>/dev/null ; then
        os_boot_entry=$(efibootmgr | awk '/BootCurrent/ { print $2 }')
        # fall back to /root/EFI_BOOT_ENTRY.TXT if it exists and BootCurrent is not available
        if [[ -z "$os_boot_entry" && -f /root/EFI_BOOT_ENTRY.TXT ]] ; then
            os_boot_entry=$(</root/EFI_BOOT_ENTRY.TXT)
        fi
        if [[ -n "$os_boot_entry" ]] ; then
            logger -s "efibootmgr -n $os_boot_entry"
            efibootmgr -n $os_boot_entry
        else
            logger -s "Could not determine value for BootNext!"
        fi
    fi
fi

flock "$TMT_TEST_PIDFILE_LOCK" tmt-reboot-core "$command" "$timeout"
